package com.dm.learn.java.thread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch，一个同步辅助类， 在完成一组正在其他线程中执行的操作之前，它允许一个或多个线程一直等待。 主要方法 public
 * CountDownLatch(int count);
 * 
 * public void countDown(); \n
 * 
 * public void await()\n
 * 
 * throws InterruptedException
 * 
 * 构造方法参数指定了计数的次数 countDown方法，当前线程调用此方法，则计数减一 awaint方法，调用此方法会一直阻塞当前线程，直到计时器的值为0
 * 
 * @author damon.han
 */
public class CountDownLatchDemo {
	final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CountDownLatch latch = new CountDownLatch(3);// 三个工人开始工作
		Worker worker1 = new Worker("张三", 3000, latch);
		Worker worker2 = new Worker("李四", 4000, latch);
		Worker worker3 = new Worker("王五", 5000, latch);
		worker1.start();//
		worker2.start();//
		worker3.start();//
		try {
			latch.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 等待所有工人完成工作
		System.out.println("all work done at " + sdf.format(new Date()));
	}

	/**
	 * 工作现场
	 * 
	 * @author damon.han
	 * 
	 */
	static class Worker extends Thread {
		String workerName;// 工作名称
		int workTime;// 工作时间
		CountDownLatch latch;

		public Worker(String workName, int workTime, CountDownLatch latch) {
			this.workerName = workName;
			this.workTime = workTime;
			this.latch = latch;
		}

		public void run() {
			System.out.println("Worker " + workerName + " do work begin at " + sdf.format(new Date()));
			doWork();// 工作了
			System.out.println("Worker " + workerName + " do work complete at " + sdf.format(new Date()));
		}

		/**
		 * 工作
		 */
		public void doWork() {
			try {
				//工作了一段时间
				Thread.sleep(workTime);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				latch.countDown();// 工人工作完成计数器减一
			}
		}
	}

}
